<template>
  <h3>jsplumb使用</h3>
  <div id="container">
    <div class="left">
      <div
        v-for="item in list1"
        :key="item.nodeId"
        :id="item.nodeId"
        name="joint"
      >
        {{ item.name }}
      </div>
    </div>
    <div class="right">
      <div
        v-for="item in list2"
        :key="item.nodeId"
        :id="item.nodeId"
        name="data"
      >
        {{ item.name }}
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted } from 'vue'
import jsPlumb from 'jsplumb'
import { useJsplumb } from './hook/useJsplumb'
import { jsplumbSetting } from './config/default'
const { jsPlumbInstance } = useJsplumb()

// 模型轴
const list1 = reactive([
  { name: 'name1', nodeId: 'name1', axis: '', type: '' },
  { name: 'name2', nodeId: 'name2', axis: '', type: '' },
  { name: 'name3', nodeId: 'name3', axis: '', type: '' },
  { name: 'name4', nodeId: 'name4', axis: '', type: '' },
  { name: 'name5', nodeId: 'name5', axis: '', type: '' },
  { name: 'name6', nodeId: 'name6', axis: '', type: '' },
])
// 接口数据点
const list2 = reactive([
  { name: '数据1', nodeId: 'data1' },
  { name: '数据2', nodeId: 'data2' },
  { name: '数据3', nodeId: 'data3' },
  { name: '数据4', nodeId: 'data4' },
  { name: '数据5', nodeId: 'data5' },
  { name: '数据6', nodeId: 'data6' },
])

onMounted(() => {
  showPlumb()
})

const showPlumb = () => {
  jsPlumbInstance.value = jsPlumb.jsPlumb.getInstance(jsplumbSetting)
  console.log('jsPlumbInstance', jsPlumbInstance.value)
  jsPlumbInstance.value.batch(() => {
    for (let i = 0; i < list1.length; i++) {
      initLeaf(list1[i].nodeId, 'joint')
    }
    for (let i = 0; i < list2.length; i++) {
      initLeaf(list2[i].nodeId, 'data')
    }
  })

  jsPlumbInstance.value.bind('click', (conn) => {
    jsPlumbInstance.value.deleteConnection(conn)
  })
}

// 初始化具体节点
const initLeaf = (id: string, type: string) => {
  const ins = jsPlumbInstance.value
  const elem = document.getElementById(id)
  if (!elem) return
  if (type === 'joint') {
    ins.makeSource(elem, {
      anchor: [1, 0.5, 0, 0], // 左 上 右 下
      allowLoopback: false,
      maxConnections: 1,
    })
  } else {
    ins.makeTarget(elem, {
      anchor: [0, 0.5, 0, 0],
      allowLoopback: false,
      maxConnections: 1,
    })
  }
}
</script>

<style scoped lang="scss">
#container {
  display: flex;
  justify-content: start;
  position: relative;
  margin-top: 20px;
  width: 100%;
  height: 300px;

  .left {
    margin: 40px;
    width: 100px;
    text-align: center;
  }

  .right {
    margin: 40px;
    width: 100px;
    text-align: center;
  }
}

.col2,
.col1 {
  float: left;
  text-align: center;
}

.col1 {
  width: 80px;
}

.col2 {
  width: 120px;
  margin-left: 80px;
}

#container > div > div {
  line-height: 30px;
  margin: 0 0 17px 0;
  background: #ef631e;
  color: #fff;
}
</style>
